package com.kayeah82.application.avatar.qq.controller;

import com.kayeah82.application.avatar.qq.exception.BusinessException;
import com.kayeah82.application.avatar.qq.exception.ErrorCode;
import com.kayeah82.application.avatar.qq.exception.ErrorEntry;
import com.kayeah82.application.avatar.qq.exception.ErrorInfo;
import com.kayeah82.application.avatar.qq.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller中异常统一捕获
 *
 * @author kayeah82
 */
@ControllerAdvice
public class ControllerBus {

    private static final Logger logger = LoggerFactory.getLogger(ControllerBus.class);

    public static void throwIfNotXhr(Throwable throwable, HttpServletRequest request) throws Throwable {
        if (!ServletUtils.isXMLHttpRequest(request)) {
            throw throwable;
        }
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Object handleRuntimeException(RuntimeException e, HttpServletRequest request)
            throws Throwable {
        logger.error("runtime exception", e);
        ErrorInfo error = ErrorEntry.build(ErrorCode.EC_10000);
        if (HttpMethod.GET.matches(request.getMethod())) {
            return error;
        }
        throwIfNotXhr(e, request);
        return error;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Object handleBusinessException(BusinessException e, HttpServletRequest request)
            throws Throwable {
        logger.error(e.getMessage());
        ErrorInfo error = ErrorEntry.build(e.getErrorCode(), e.getMessage());
        if (HttpMethod.GET.matches(request.getMethod())) {
            return error;
        }
        throwIfNotXhr(e, request);
        return error;
    }

}
